package com.smart.thirteen.keyholder;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author junrui.wang
 * @create 2019/10/21
 */
public class KeyHolderTest {
    public static void main(String[] args) throws SQLException {
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath*:com/smart/thirteen/applicationContext-template.xml");
        JdbcTemplate jdbcTemplate = (JdbcTemplate) ac.getBean("jdbcTemplate");

        final String sql = "INSERT INTO t_topic(topic_title,user_id) VALUES (?, ?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                //PreparedStatement preparedStatement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                PreparedStatement preparedStatement = con.prepareStatement(sql);
                preparedStatement.setString(1, "test2");
                preparedStatement.setString(2, "222");
                return preparedStatement;
            }
        }, keyHolder);
        System.out.println(keyHolder.getKey().intValue());

    }
}
